<?php

namespace App\services;
use Illuminate\Support\Facades\Redis;
use Monolog\Handler\StreamHandler;
use Monolog\Logger;

class Wechat
{
    //获取小程序access_token
    public static function getAccessToken()
    {

        $appid = 'wxbb2bda0148fea6f3';
        $secret = 'd119a5915438f716d16d4982f9c0e022';
        if(Redis::get('access_token_applets')){
            return Redis::get('access_token_applets');
        }
        $url = 'https://api.weixin.qq.com/cgi-bin/stable_token';
        $data = [
            'grant_type' => 'client_credential',
            'appid' => $appid,
            'secret' => $secret
        ];
        $rt =  httpPostRequest($url, $data);
        $rt = json_decode($rt,true);

        if(!isset($rt['access_token'])){
            return error($rt['errmsg']);
        }
        Redis::setex('access_token_applets',7200,$rt['access_token']);
        return $rt['access_token'];



    }
    /***
     * @param $path
     * @param $query
     * @return bool|string
     * @throws \Exception
     */
    //生成URL LINK
    public static function getUrlLink($path = '/pages/index/index',$query = '')
    {
        $asscess_token = static::getAccessToken();
        $url = 'https://api.weixin.qq.com/wxa/generate_urllink';
        $data = [
            'path' => $path,
            'query' => $query
        ];
        $common_parameters = [
            'access_token' => $asscess_token
        ];
        $rt = httpPostRequest($url,$data,$common_parameters);
        return $rt;
    }

    public static function createQrCode()
    {
        $asscess_token = static::getAccessToken();
        $url = 'https://api.weixin.qq.com/cgi-bin/qrcode/create';
        $common_parameters = [
            'access_token' => $asscess_token
        ];
        $uuid = uuid();
        $data = [
            'expire_seconds'  => 60,
            'action_name'=> 'QR_STR_SCENE',
            'action_info' => ['scene'=>['scene_str'=>$uuid]]
        ];
        $rt = httpPostRequest($url,$data,$common_parameters);
        $rt = json_decode($rt,true);
        if(array_key_exists('errcode',$rt) && $rt['errcode'] == 40001){
            Redis::del('access_token_applets');
            self::getAccessToken();
        }
        $rt = httpPostRequest($url,$data,$common_parameters);
        $rt = json_decode($rt,true);
        $rt['qr_code_url'] =  'https://mp.weixin.qq.com/cgi-bin/showqrcode?ticket='.$rt['ticket'];
        $rt['uuid'] = $uuid;
        return $rt;

    }

}
